package com.util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.poi.util.IOUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

/**
 * @author: cxt
 * @time: 2021/6/8
 * 发送http请求工具类
 *
 * <dependency>
 * <groupId>commons-httpclient</groupId>
 * <artifactId>commons-httpclient</artifactId>
 * <version>3.1</version>
 * </dependency>
 */
@Log4j2
public class HTTPRequestUtil {

    /**
     * post请求
     *
     * @param url 请求地址
     */
    public static byte[] sendPost(String url) {
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置连接服务器超时时间 10秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        // 创建post请求
        PostMethod postMethod = new PostMethod(url);
        // 设置post请求超时时间 半分钟
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000);
        byte[] body = null;
        try {
            httpClient.executeMethod(postMethod);
            body = postMethod.getResponseBody();
            // 关闭连接
            postMethod.releaseConnection();
        } catch (IOException e) {
            log.error("http请求设置请求方式出错");
            e.printStackTrace();
        }
        return body;
    }

    /**
     * get请求
     *
     * @param url 请求地址
     */
    public static byte[] SendGet(String url) {
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置连接服务器超时时间 10秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000);
        getMethod.addRequestHeader("Content-Type", "application/json");
        byte[] body = null;
        try {
            httpClient.executeMethod(getMethod);
            if (200 == getMethod.getStatusCode()) {
//                body = getMethod.getResponseBody();
                // getResponseBody 会在较大请求时候抛出异常
                InputStream stream = getMethod.getResponseBodyAsStream();
                body = IOUtils.toByteArray(stream);
            }
            getMethod.releaseConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    /**
     * 使用resTemplate请求
     *
     * @param contentType 请求数据格式 application/json、video/mp4
     * @param url         url地址
     * @param method      请求方式
     * @param map         请求参数
     * @return 结果
     */
    public static HashMap resTemplate(MediaType contentType, String url, HttpMethod method, HashMap<String, Object> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(contentType);
        try {
            // RestTemplate restTemplate = SpringBeanHelper.getBean(RestTemplate.class); // 从容器中取对象
            RestTemplate restTemplate = new RestTemplate();
            HashMap result = restTemplate.exchange(url, method, new HttpEntity<>(map, headers), HashMap.class).getBody();
            if (result != null) {
                String code = (String) result.get("code");
                if ("200".equals(code)) {
                    log.info(String.valueOf(result));
                    return result;
                } else {
                    log.error("请求失败");
                }
            }
        } catch (HttpClientErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url         发送请求的 URL
     * @param param       请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static String queryGet(String url, String param, String contentType) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }


    // 测试
    public static void main(String[] args) {
        File file = new File("F://emoji.json");
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            FileOutputStream fileOutputStream = null;
            String url = null;
            int i = 0;
            long l = System.currentTimeMillis();
            while ((url = reader.readLine()) != null) {
                i++;
                byte[] bytes = SendGet(url);
                fileOutputStream = new FileOutputStream(new File("E://img/" + i + ".png"));
                fileOutputStream.write(bytes);
                fileOutputStream.close();
            }
            reader.close();
            // 查看耗时
            System.out.println(System.currentTimeMillis() - l);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
